package com.boot.netty.server.listener;

import com.boot.netty.commons.codec.marshalling.MarshallCodeFactory;
import com.boot.netty.server.config.NettyServerConfig;
import com.boot.netty.server.handler.ServerChannelHandlerAdapter;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class ServerListener {

    @Autowired
    private NettyServerConfig nettyServerConfig;

    @Autowired
    private ServerChannelHandlerAdapter serverChannelHandlerAdapter;

    private EventLoopGroup acceptorGroup;
    private EventLoopGroup workGroup;
    private ServerBootstrap serverBootstrap;

    private void init(){
        this.acceptorGroup = new NioEventLoopGroup();
        this.workGroup = new NioEventLoopGroup();
        this.serverBootstrap = new ServerBootstrap();
        this.serverBootstrap.group(acceptorGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100)
                .handler(new LoggingHandler(LogLevel.INFO));
    }

    public ServerListener(){
        init();
    }


    /**
     * 关闭服务器方法
     */
    @PreDestroy
    public void close() {
        log.info("关闭netty服务器");
        acceptorGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
    }

    public void startNettyServer(){

        this.serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new IdleStateHandler(5, 0, 0, TimeUnit.SECONDS))
                        .addLast(MarshallCodeFactory.deCoder())
                        .addLast(MarshallCodeFactory.enCoder())
                        .addLast(serverChannelHandlerAdapter);
            }
        });

        try {
            log.info("netty服务器正在监听端口:[{}]",nettyServerConfig.getPort());
            ChannelFuture future = serverBootstrap.bind(nettyServerConfig.getPort()).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.info("NettyServer 出现异常关闭{} 异常原因{}",this.getClass(),e.getMessage());
        }finally {
            acceptorGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
    
}
